<?php
/**
 * 会员
 */
namespace User\Controller;
use Common\Controller\MemberbaseController;
class AuthController extends MemberbaseController {
	function _initialize() {}
	
	public function index()
	{
		//$taskData=$this->checkTask(13);
		//print_r($taskData);
		//$pubdata=M("Pubwechat")->where(array("id"=>11))->find();
		//header("Location: ".$pubdata["wechatarticle"]);
		//header("Location: weixin://profile/".$pubdata['pwc_id']);
	
	
		//$this->success("成功完成任务");
		
	}
	
	public function wechat()
	{
		header("Content-Type: text/html; charset=utf-8");
		
		$uid=I("get.uid",0,"intval");
		$creattime=I("get.creattime","","trim");
		$where["id"]=$uid;
		$data=M("user")->where($where)->find();
		if(!$data){$this->error("用户信息不存在");}
		if($data["user_status"]==0){$this->error("该用户已被禁用"); }
		if($data["user_status"]==2){$this->error("该用户未验证"); }
		if($data["user_type"]!=2){$this->error("此类型用户不能绑定微信号"); }
		if(empty($data["creattime"])||$data["creattime"]!=$creattime){$this->error("验证未通过，请重新获取二维码信息");}
		$Grant=AuthJI();
		$options=get_site_options();
		$redirect_uri=$options["site_host"].U("Auth/getCode",array("uid"=>$uid));
		header("Location: ".$Grant->get_authorize_url($redirect_uri));
	}
//获取返回的codexinxi
	public function getCode()
	{
		header("Content-Type: text/html; charset=utf-8");
		$code=I("get.code");
		$uid=I("get.uid",0,"intval");
		
		if($uid==0){$this->error("用户信息丢失"); }
		if(empty($code)){$this->error("获取code失败");}
		$Grant=AuthJI();
		$ACESS_TOKEN=$Grant->get_access_token($code);
		if(!$ACESS_TOKEN){$this->error("获取access_token失败");  }
		//获取用户信息
		$userInfo=$Grant->get_user_info($ACESS_TOKEN["access_token"],$ACESS_TOKEN["openid"]);
		if(!$userInfo){ $this->error("拉取微信用户信息失败");  }
		$this->addUserCanyu($userInfo,$uid);
		$this->index();
	}
	
	private function addUserCanyu($data,$uid)
	{
		/*"openid": "oLVPpjqs9BhvzwPj5A-vTYAX3GLc",
		"nickname": "方倍",
		"sex": 1,
		"language": "zh_CN",
		"city": "Shenzhen",
		"province": "Guangdong",
		"country": "CN",
		"headimgurl": "http://wx.qlogo.cn/mmopen/utpKYf69VAbCRDRlbUsPsdQN38DoibCkrU6SAMCSNx558eTaLVM8PyM6jlEGzOrH67hyZibIZPXu4BK1XNWzSXB3Cs4qpBBg18/0",
		"privilege": []
		
		openid 	用户的唯一标识
		nickname 	用户昵称
		sex 	用户的性别，值为1时是男性，值为2时是女性，值为0时是未知
		province 	用户个人资料填写的省份
		city 	普通用户个人资料填写的城市
		country 	国家，如中国为CN
		headimgurl 	用户头像，最后一个数值代表正方形头像大小（有0、46、64、96、132数值可选，0代表640*640正方形头像），用户没有头像时该项为空
		privilege 	用户特权信息，json 数组，如微信沃卡用户为（chinaunicom）		
		*/
	  //用到的表 wechatnumber
	    $this->cheackRepeAt($data["openid"]);
	    $data["uid"]=$uid;
	    $data["addtime"]=time();
	   $result=M("wechatNumber")->add($data);
        if($result)
        {
            $udata["creattime"]="";
            M("user")->where("id=$uid")->save($udata);
          $this->success("您的微信昵称为{$data['nickname']}已绑定成功");
        }else{
           $this->error("绑定失败");
        }
	}
	//检测是否存在重复的openid 值
	private function cheackRepeAt($openid)
	{
	   $where["openid"]=$openid;       
	    $result=M("WechatNumber")->where($where)->find();
	    if(!empty($result)){ $this->error("此微信已绑定。请勿重复操作"); }
	}
	//
	private function result($type,$msg)
	{
	     $mod=$type="succ"?$type:"err";
	     $this->assign("msg",$msg);
	     $this->assign("mod",$mod);
	     $this->display("result");
	     die();
	}
	public function error($msg)
	{
	       $this->result("err",$msg);
	}
	public function success($msg)
	{
	       $this->result("succ",$msg);
	}
	
	//一下为做任务赚积分环节
	//执行任务
	public function makeTask()
	{
		$uid=I("get.uid",0,"intval");
		$rid=I("get.rid",0,"intval");
		if($uid==0||$rid==0){$this->error("数据丢失，无法完成任务");}
		$taskData=$this->checkTask($rid);
		if($taskData["ownuid"]!=$uid)
		{
			$this->error("任务信息检测发现异常，暂时不能做此任务");
		}
		if($taskData["status"]==2)
		{
			$this->error("任务已关闭");
		}
		if(!isset($_SESSION["openid"]))
		{	
			//获取用户openid信息
			$Grant=AuthJI();
			$options=get_site_options();
			$redirect_uri=$options["site_host"].U("Auth/getTaskCode",array("uid"=>$uid,"rid"=>$rid));
			header("Location: ".$Grant->get_authorize_baseurl($redirect_uri));
			die();
		}
		//检测当前openid是否已被绑定
		$WWHERE["openid"]=$_SESSION["openid"];
		$pResult=M("wechatNumber")->where($WWHERE)->find();
		if(!$pResult){$this->error("请先绑定微信账号信息");}
		if($pResult["uid"]==$uid){$this->error("不能做自己发布的任务");}
		//检测发任务用户积分是否足够
		//获取发任务账务信息用户账户信息
		$account=getUserAccont($uid);
		if($account["available_funds"]<$taskData["integration"]){ $this->error("任务发布用户，积分不足。请稍后完成此任务");}
		//修改账户信息
		TransferAccounts($uid,$pResult["uid"],$taskData["reward"],$taskData["integration"]);
		//记录任务信息
		addTaskLog($uid,$pResult["uid"],$rid,$taskData["reward"],$taskData["tasktype"]);
		//解析二维码图像
		if($taskData["tasktype"]=1)
		{
			//获取公众号的二维码信息
			$pwhere["id"]=$taskData["tasktitle"];
			$pubdata=M("Pubwechat")->where($pwhere)->find();
	/*		if(empty($pubdata["ercodeurl"]))
			{
				$options=get_site_options();
				$pwc_ewm=$options["site_host"].$pubdata["pwc_ewm"];
				$ercodeurl=recognitionErCode($pwc_ewm);
				$pdata["ercodeurl"]=$ercodeurl;
				M("Pubwechat")->where($pwhere)->save($pdata);
				$pubdata["ercodeurl"]=$ercodeurl;
			}
	*/	
			$shebei=$this->checekPhoneType();
			if($shebei=="iphone")
			{
				header("Location: ".$pubdata["wechatarticle"]);  //发布一篇公众号文章；
			}else{
				header("Location: weixin://profile/".$pubdata['pwc_id']);
			}
		}else{
			header("Location: ".$taskData["tasktitle"]);
		}
		
		

	}
	
	//检测设备
	public  function checekPhoneType()
 	{
		$user_agent=$_SERVER["HTTP_USER_AGENT"];		 
 		if (preg_match("/iphone/i",$user_agent)){
			return "iphone";
 		}elseif(preg_match("/android/i",$user_agent)){ 
 			return "android";
 		}
	}
	
	/*
	 * 获取做任务微信用户返回code 
	 */
	public function getTaskCode()
	{
		$code=I("get.code");
		$uid=I("get.uid",0,"intval");
		$rid=I("get.rid");
		if(empty($code)){$this->error("获取code失败");}
		$Grant=AuthJI();
		$ACESS_TOKEN=$Grant->get_access_token($code);
		if(!$ACESS_TOKEN){$this->error("获取access_token失败");}
		$_SESSION["openid"]=$ACESS_TOKEN["openid"];
		$options=get_site_options();
		$URL=$options["site_host"]."/index.php/user/Auth/makeTask/uid/".$uid."/rid/".$rid;
		header("Location: ".$URL);
	}
	
	protected  function checkTask($rid)
	{
		$where["tid"]=$rid;
		$data=M("taskList")->where($where)->find();
		if($data)
		{
			return $data;	
		}else{
			$this->error("不存在当前任务");
		}
	}
	protected  function getUser($uid)
	{
		$where["id"]=$uid;
		$userdata=M("User")->where($where)->find();	
		if(!$userdata){$this->error("无法获取用户信息");}
		return $userdata;
	}

	
	
	
	
	
}